﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demos.DesignPatterns._13_代理模式
{
    /// <summary>
    /// 
    /// </summary>
    class ShopCachedCartProxyService : ICartService
    {
        private readonly ICartService _realService;
        private readonly ConcurrentDictionary<string, ShopCartObject> _cache = new();

        public ShopCachedCartProxyService(ICartService cartService)
        {
            _realService = cartService;
        }
        public ShopCartObject GetCart(string userId)
        {
            return _cache.GetOrAdd(userId, id =>
            {
                Console.WriteLine($"[缓存] 未找到用户 {id} 的购物车缓存");
                return _realService.GetCart(id);
            });
        }

        public void SaveCart(ShopCartObject cart)
        {
            _realService.SaveCart(cart);
            _cache.AddOrUpdate(cart.UserId, cart, (_, _) => cart);
            Console.WriteLine($"[缓存] 更新用户 {cart.UserId} 的购物车缓存");
        }

        public void AddToCart(string userId, ShopCartItem item)
        {
            var cart = GetCart(userId);
            cart.AddItem(item);
            SaveCart(cart);
        }

        public void ClearCart(string userId)
        {
            _realService.ClearCart(userId);
            _cache.TryRemove(userId, out _);
            Console.WriteLine($"[缓存] 移除用户 {userId} 的购物车缓存");
        }


    }
}
